package com.example.httpprocessor.http;

import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.util.Map;

import javax.inject.Inject;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OKHttpProcessor implements IHttpProcessor{

    private OkHttpClient mOkHttpClient;
    private Handler myHandler;

    //  初始化数据
    @Inject
    public OKHttpProcessor() {
        mOkHttpClient = new OkHttpClient();
        myHandler = new Handler(Looper.myLooper());//  线程调度器  也可以用  rxjava
    }


    @Override
    public void post(String url, Map<String, Object> params, HttpCallback callback) {

        //  在这里写请求数据  然后把返回来的数据返回去
        final RequestBody requestBody = appendBody(params);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    final String result = response.body().string();
                // 把请求数据返回来的结果返回去
                if (response.isSuccessful()) {
                    //  通过线程调度器返回
                    myHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onSuccess(result);
                        }
                    });
                } else {
                    myHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFailure(result);
                        }
                    });
                }
            }
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                callback.onFailure(e.toString());
            }
        });


    }

    private RequestBody appendBody(Map<String,Object> params){

        FormBody.Builder body = new FormBody.Builder();
        if (params ==  null || params.isEmpty()) {
            return body.build();
        }
        for (Map.Entry<String, Object> entry : params.entrySet()){
            body.add(entry.getKey(),entry.getValue().toString());
        }
        return body.build();
    }

}
